/**
 * 保存本地文件
 */
var recorder;
// 已经保存的文件
var SAVEFILES = {}, saveFiles_key = 'SAVEFILES';
var USER_PATH = '';
var recordingId = null;
function initSaveFile() {
    SAVEFILES = api.getPrefs({key: saveFiles_key, sync: true});
    if(SAVEFILES) {
        SAVEFILES = JSON.parse(SAVEFILES);
    }else {
        SAVEFILES = {};
    }
    var custId = USER.Get('custId');
    USER_PATH = 'record'+custId;
    if(SAVEFILES[USER_PATH]) {
        // 已经初始化过了
    }else {
        SAVEFILES[USER_PATH] = {};
    }
}

/**
 * [getIsSave 录音文件是否保存]
 * @Author ljliu    2020-02-09T17:50:34
 * @param  {string} id              需要录音的ID
 * @return {是否保存}                未保存：null 以保存：本地路径
 */
function getIsSave(id) {
    var localPath = SAVEFILES[USER_PATH][id];
    var localData = JSON.stringify(SAVEFILES);
    console.log(id + '读取录音文件:=====>'+localData);
    if(localPath) {
        return localPath;
    }
    return null;
}

/**
 * [saveFileById 保存录音文件]
 * @Author ljliu    
 * @param  {[type]} id        [文件ID]
 * @param  {[type]} path      [文件路径]
 */
function saveFileById(id, path) {
    var userFolder = SAVEFILES[USER_PATH];
    userFolder[id] = path+'';
    var localData = JSON.stringify(SAVEFILES);
    console.log('保存录音文件:=====>'+localData);
    api.setPrefs({
        key: saveFiles_key,
        value: localData,
    });
}

function clearFileById() {
    api.setPrefs({
        key: saveFiles_key,
        value: '',
    });
}

function createFile(id, callback) {
    console.log('createFile========='+id);
    if(recordingId) {
        stopRecord();
        return;
    }
    recordingId = id + '';
    recorder = api.require('audioRecorder');
    var resultList = api.hasPermission({
        list: ['microphone']
    });
    var startRecord = function() {
        api.showProgress({
            style: 'default',
            animationType: 'fade',
            title: '录音启动中...',
            modal: true
        });
        recorder.startRecord({
            savePath: 'fs://audioRecorder/audio'+recordingId+'.pcm',
            format: 'pcm'
        }, function(ret, err) {
            api.hideProgress();
            if(err || !ret.status) {
                console.error('打开录音失败>>>>'+ JSON.stringify(err));
                fnToast('打开录音失败');
                recordingId = null;
                callback();
            }else {
                console.info('打开录音成功');
                callback(true);
            }
        });
    };
    if(resultList[0]['granted']+'' != 'false') {
        startRecord();
    }else {
        api.requestPermission({
            list: ['microphone']
        },function(ret) {
            if(ret && ret.list) {
                var cancle = []
                for(var i = 0; i < ret.list.length; i ++) {
                    if(!ret.list[i]['granted']) {
                        cancle.push(ret.list[i]['name']);
                    }
                }
                if(cancle.length >0) {
                    fnToast('您没有允许录音权限，请允许后继续');
                    recordingId = null;
                    callback()
                }else {
                    startRecord();
                }
            }
        })
    }
}


function stopRecord(callback) {
    console.log('stopRecord========='+recordingId);
    recorder.stopRecord(function(ret) {
        var path = 'fs://audioRecorder/audio'+recordingId+'.pcm',
            mp3File = path.replace('.pcm', '.mp3');
        console.log('audioPaht======'+path);
        console.log('mp3Path======'+mp3File);
        recordingId = null;
        if(!ret.status) {
            fnToast('录音失败');
        }else {
            // callback && callback(path);
            api.showProgress({
                style: 'default',
                animationType: 'fade',
                title: '录音保存中...',
                modal: true
            });
            recorder.covertToMp3({
                channel: 2,
                sampleRates: 16000,
                originalFilePath: path,
                mp3FilePath: mp3File
            }, function(ret) {
                console.log('录音PCM转化mp3成功');
                api.hideProgress();
                if(ret.status) {
                    callback && callback(mp3File);
                }
            });
        }
    });
}
